#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanXuchangPolicy(BaseTaxPolicySpider):
    name = 'henan_xuchang_jianan_policy'
    
    province = '河南省'
    city = '许昌市'
    # county = '滑县'
    park = ''

    custom_settings = {
        "DOWNLOAD_TIMEOUT": 60
    }
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
        # "X-Requested-With": "XMLHttpRequest"
    }

    def start_requests(self):
        for source, county, url, path in [
            ['许昌市建安区人民政府', "建安区", "http://www.jianan.gov.cn/govxxgkgfxwjlist.html", "首页>政府信息公开>法定主动公开内容>政府文件>部门文件"],
            ['许昌市建安区人民政府', "鄢陵县", "http://www.yanling.gov.cn/govxxgkgfxwjlist.html", "首页>政府信息公开>法定主动公开内容>政府文件>部门文件"],
        ]:

            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item, 'path': path}, dont_filter=True)

    def parse_content(self, response, **kwargs):
        meta = response.meta
        gov_listTwoPage = response.xpath("//script").re_first(r'="(.*Common\.js)"')
        yield response.follow(gov_listTwoPage, callback=self.parse_js1, meta=meta, dont_filter=True)

    def parse_js1(self, response, **kwargs):
        meta = response.meta
        projectName = response.xpath(""".""").re_first(r'projectName"\s*:\s*"(.*?)"')
        meta['projectName'] = projectName
        yield response.follow('/js/govxxgkgfxwjlist.js', callback=self.parse_js2, meta=meta, dont_filter=True)

    def parse_js2(self, response, **kwargs):
        meta = response.meta
        siteGuid = response.xpath(""".""").re_first(r'siteGuid"?\s*[=:]+\s*"(.*?)"')
        deptcode = response.xpath(""".""").re_first(r'deptcode\s*=\s*"(.*?)"')
        catenum = response.xpath(""".""").re_first(r'catenum\s*=\s*"(.*?)"')
        category_api = response.xpath(""".""").re_first(r'projectName\s*\+\s*"(.*?getGovInfoListByCategoryNum.*?)"')
        projectName = response.meta['projectName']
        data = {
            "deptcode": deptcode,
            "siteGuid": siteGuid,
            "pageIndex": "0",
            "pageSize": "100",
            "categoryNum": catenum
        }
        meta['data'] = data
        meta['projectName'] = projectName
        # data = json.dumps(data, separators=(',', ':'))
        # print(data)
        url = response.urljoin(projectName + category_api)
        yield scrapy.FormRequest(url, formdata=data, callback=self.parse_list, meta=meta, headers=self.headers,
                                 method="POST", dont_filter=True)

    def parse_list(self, response, **kwargs):
        # print(response.request)
        prev_item = response.meta.get('item')
        datas = json.loads(response.json()['custom'])['data'][0]
        elem_list = datas['infolist']
        for elem in elem_list:
            item = Item()
            item['source_url'] = f"/govxxgkgfxwjdetail.html?infoid={elem['infoid']}&type=1"
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['infodate']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if 'xlsx' in item['source_url'] or 'doc' in item['source_url'] or 'pdf' in item['source_url']:
                continue
            print(response.url, elem['infourl'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            data = response.meta['data']
            pages = math.ceil(int(datas['total']) / 100)
            print(response.url, f"page: {pages}")
            for page_num in range(1, int(pages) + 1):
                data['pageIndex'] = str(page_num)
                # temp_data = json.dumps(data, separators=(',', ':'))
                yield scrapy.FormRequest(response.url, formdata=data, callback=self.parse_list, headers=self.headers,
                                         meta={'item': prev_item, 'is_next': False},  method="POST", dont_filter=True)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_xuchang_jianan_policy".split())
